{% extends "base.html" %}
{% load diggpaginator %}

{% block title %}Liste des machines{% endblock %}
{% block content_title %}Liste des machines{% endblock %}
{% block image %}<img src="/media/images/oxygen/search.png" />{% endblock %}
{% block extrajs %}
  {{ block.super }}
  <script type="text/javascript" src="{{ MEDIA_URL }}js/clariadmin.js"></script>
  <script type="text/javascript" charset="utf-8">
    dojo.require("dijit.Menu");
    dojo.require('dijit.form.MultiSelect');
    dojo.require('dijit.form.CheckBox');
    dojo.require("dojox.validate");
    dojo.require("dijit.layout.ContentPane");

    dojo.addOnLoad(function()
    {
      dojo.forEach(dojo.query(".clickable_rows"), function(row)
      {
        create_menu(row.id, row.children[0].textContent);
        dojo.forEach(row.getElementsByTagName("td"), function( elem )
        {
            if (! dojo.hasClass(elem, "unclickable"))
            {
                dojo.connect(elem, "onclick", showHostPane);
            }
        });
      });
      var global_search = dojo.byId("id_global_search");
      if (global_search)
        global_search.focus();

      dojo.connect(dijit.byId("id_os"),"onKeyUp",validateIfEnter);
      dojo.connect(dijit.byId("id_type"),"onKeyUp",validateIfEnter);
      dojo.connect(dijit.byId("id_supplier"),"onKeyUp",validateIfEnter);
      dojo.connect(dijit.byId("id_site"),"onKeyUp",validateIfEnter);
      dojo.connect(dijit.byId("id_type"),"onChange",typeChanged);
    });

    var openedRow=null;
    function clearOpenedRow(){
      if(openedRow){
        dojox.fx.wipeOut({
            node:openedRow,
            duration:200,
        }).play();
        dijit.byId(openedRow.children[0].children[0].id).set('content','');
        openedRow = null;
     }
    }
     var hilighted_row=false;
    function showHostPane(e){
      e = e || event;
      var target = e.srcElement || e.target;
      if(! (hilighted_row)){
        host_id = target.parentNode.id.replace('comp_','');
        hilighted_row=true;
        highlight("comp_"+host_id, 500, '#ff6a6a', function(){hilighted_row=false;});
        if(openedRow == dojo.byId('edit_row_'+host_id))
          return clearOpenedRow();
        clearOpenedRow();
        openedRow = dojo.byId('edit_row_'+host_id);
        pane = dijit.byId('pane_row_'+host_id);
        dojo.xhrGet({
          url:"{% url clariadmin.views.modify -1 %}".replace('-1',host_id),
          load:function(data){
            pane.set('content',data);
            dojo.connect(dijit.byId("id_"+host_id+"-type"),"onChange",ajaxTypeChanged);
            dojo.connect(dijit.byId("the_"+host_id+"_form"), "onsubmit", ajaxFormSubmit);
            openedRow.classList.remove('dijitHidden');
            dojox.fx.wipeTo({
                node:openedRow,
                duration: 600,
                height: 500,
            }).play();
            if (hilighted_row)
              scrollAndHighlight(dojo.byId("comp_"+host_id), 200,false);
            else
              scrollAndHighlight(dojo.byId("comp_"+host_id), 200, 900);
          }
        });
      }
    }

    function typeChanged(event){
      var select_box = dijit.byId("id_type");
      dojo.xhrGet({
          url: "{% url clariadmin.views.ajax_extra_fields_form -1 '/b' %}".replace('-1',select_box.item.value?select_box.item.value:-1),
          handleAs: "text",
          load: function(data){
            tab = dojo.byId("extra_fields");
            dojo.forEach(dijit.findWidgets(tab), function(w) {w.destroyRecursive();});
            tab.innerHTML = data;
            dojo.parser.parse(tab);
          }
      });
    }

    function create_menu(target_id, host_name) {
      pMenu = new dijit.Menu({
          targetNodeIds: [target_id,],
      });
      target_id = target_id.replace("comp_","");
      pMenu.addChild(new dijit.MenuItem({
            label: "Éditer "+host_name,
            iconClass: "dijitEditorIcon dijitEditorIconSave",
            onClick: function() {
              document.location.href = "{% url clariadmin.views.modify -1 %}".replace("-1", target_id);},
      }));
      pMenu.addChild(new dijit.MenuItem({
          label: "Suprimer "+host_name,
          iconClass: "dijitEditorIcon dijitEditorIconDelete",
          onClick: function() {
              confirmDialog("Supression de l'hote", "êtes vous sûr de vouloir supprimer cette machine de la base?",
                            confirmation_callback,
                            "{% url clariadmin.views.modify -1 %}".replace("-1", target_id));
          }
      }));
      pMenu.addChild(new dijit.MenuItem({
            label: "Éditer une copie de "+host_name,
            iconClass: "dijitEditorIcon dijitEditorIconCopy",
            onClick: function() {
              document.location.href = "{% url clariadmin.views.new -1 %}".replace("-1", target_id);
            },
      }));
      pMenu.startup();
    }

    function ajaxTypeChanged(event){
      host_id=this.name.replace('-type','');
      select_box=this;
        dojo.byId(host_id+"extra_fieldset").classList.remove("dijitHidden");
        dojo.xhrGet({
            url:"{% url clariadmin.views.ajax_extra_fields_form host_type_id=-1 prefix=9467 %}"
                    .replace('-1',select_box.item.value?select_box.item.value:-1)
                    .replace('9467',host_id),
            load: function(data){
                  tab = dojo.byId(host_id+"extra_fields");
                  dojo.forEach(dijit.findWidgets(tab), function(w) {w.destroyRecursive();});
                  tab.innerHTML = data;
                  dojo.parser.parse(tab);
                }
            });
    }

    // même en utilisant dojo.disconnect, il arrivait d'avoir plusieur formSubmit.
    var post_running=false;
    function ajaxFormSubmit(evt) {
      if(!post_running){
        post_running=true;
        dojo.stopEvent(evt);
        var form = evt.srcElement || evt.target;
        host_id = form.id.replace('the_','').replace('_form','');
        pane = dijit.byId('pane_row_'+host_id);
        console.log(form);
        dojo.xhrPost({
            form: form.id,
            handleAs: "text",
            load: function(data) {
              pane.set('content',data);
              dojo.connect(dijit.byId("id_"+host_id+"-type"),"onChange",ajaxTypeChanged);
              dojo.connect(dijit.byId("the_"+host_id+"_form"), "onsubmit", ajaxFormSubmit);
              console.log(dojo.query("#"+pane.id+" ul.errorlist"))
              if(dojo.query("#"+pane.id+" ul.errorlist")[0])
                highlight(pane.id, 500, '#ff6a6a', function(){});
              else
                highlight(pane.id, 800, '#6aff6a', function(){});
              post_running=false;
            }
        });
      }
    }

    function confirmation_callback(myBool, form_url){
        if(myBool)
            postwith({delete: "true"}, form_url);
    }

    function validateIfEnter(ievent) {
      if (ievent.keyCode == 13) {
        dojo.byId("search_form").submit();
      }
    }
  </script>

{% endblock %}
{% block content %}

  {% if form.security_can_view %}
    <form method="post" id="search_form">
      {% csrf_token %}
      <fieldset class="block form">
        <legend>Filtrage</legend>
        <table class="search">
          {{ form.as_column_table }}
        </table>
        <table id="extra_fields" class="search">{%if form_extra%}{{form_extra.as_table}}{%else%}<tr><td></td></tr>{%endif%}</table>
        <div class="left_buttons">
          <button type="reset" iconClass="dijitrtl dijitIconClear" dojoType="dijit.form.Button">Annuler</button>
        </div>
        <div align='center'>
          <button type="submit"  dojoType="dijit.form.Button" iconClass="dijitrtl dijitIconSearch">Rechercher</button>
        </div>
      </fieldset>
    </form>
  {% else %}
    <p>Vous n'avez aucune permission de recherche.</p>
  {% endif %}

  {% if page.object_list %}
    {% if page.paginator.num_pages > 1 %}
      {% diggpaginator page %}
    {% endif %}
    <table class="resultat" id="clariadmin_result_all">
      <thead>
        <tr>{%for column in columns %}
          <th><a href="?sort={% if sorting == column %}-{% endif %}{{ column }}">{% if sorting == column %}
              <img src="/media/images/oxygen/arrow-up.png" class="state_image" alt="down" />{% else %}{% if sorting == '-'|add:column %}
              <img src="/media/images/oxygen/arrow-down.png" class="state_image" alt="up" />{% endif %}{% endif %}
            {{ column }}</a></th>{% endfor %}
        </tr>
      </thead>
      <tbody id="context_lines">
          {% for row in page.object_list %}
          <tr id='comp_{{ row.id }}' class='{% cycle 'row1' 'row2'%} clickable_rows'>
          {% if 'hostname' in columns %}<td class="unclickable"><a href='{% url clariadmin.views.modify row.id %}'>{{ row.hostname }}</a></td>{% endif %}
          {% if 'ip' in columns %}<td class="unclickable">{{ row.ip }}</td>{% endif %}
          {% if 'site' in columns %}<td><a href="{% url list_hosts row.site.id %}">{{ row.site }}</a></td>{% endif %}
          {% if 'type' in columns %}{% if row.type %} <td style='color:{{row.type.color_fg}};background-color:{{row.type.color_bg}}'>{{ row.type }}</td>{% else %} <td></td> {% endif %}{% endif %}
          {% if 'os' in columns %}<td>{{ row.os }}</td>{% endif %}
          {% if 'model' in columns %}<td>{{ row.supplier.name }}{% if row.model %} - {{ row.model }}{% endif %}</td>{% endif %}
          {% if 'status' in columns %}<td style='background-color:{{ row.status.color_bg }};color:{{ row.status.color_fg }}'>{{ row.status.name }}</td>{% endif %}
          {% if 'additionnal_fields' in columns %}<td>{% for f in row.additionnalfield_set.all %}{% if f.field.show and f.value_readable %}<b>{{f.field.name}}:</b>{{f.value_readable}}, {% endif %}{% endfor %}</td>{% endif %}
        </tr>
        <tr class="dijitHidden" id="edit_row_{{ row.id }}" ><td colspan="99"><div dojoType="dijit.layout.ContentPane" id="pane_row_{{ row.id }}"></div></td></tr>
        {% endfor %}
      </tbody>
    </table>
    {% if page.paginator.num_pages > 1 %}
      {% diggpaginator page %}
    {% endif %}
  {% endif %}
{% endblock %}
